package com.ym.soso.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ym.base.enums.FlagEnum;
import com.ym.common.utils.StringUtil;
import com.ym.core.shiro.ShiroUtil;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.enums.CodeRuleEnum;
import com.ym.medical.enums.TheBelongEnum;
import com.ym.medical.service.ISysCodeRuleSV;
import com.ym.soso.dao.ChinaMedicineDao;
import com.ym.soso.domain.entity.ChinaMedicineEntity;
import com.ym.soso.domain.entity.RegistryWayEntity;
import com.ym.soso.domain.param.ChinaMedicineMobileQueryParam;
import com.ym.soso.domain.param.ChinaMedicineQueryParam;
import com.ym.soso.domain.param.ChinaMedicineUpdateParam;
import com.ym.soso.domain.param.PublishParam;
import com.ym.soso.domain.param.RegistryWayUpdateParam;
import com.ym.soso.domain.vo.ChinaMedicineListPcVO;
import com.ym.soso.domain.vo.ChinaMedicineVO;
import com.ym.soso.service.IChinaMedicineSV;
import com.ym.soso.service.IRegistryWaySV;
import com.ym.soso.service.search.service.ChinaMedicineIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 中医堂信息Service业务层处理
 *
 * @author ym
 * @date 2020-09-01
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ChinaMedicineSVImpl extends BaseSVImpl<ChinaMedicineEntity, ChinaMedicineDao> implements IChinaMedicineSV {

    @Autowired
    private ISysCodeRuleSV sysCodeRuleSV;

    @Autowired
    private IRegistryWaySV registryWaySV;

    @Autowired
    private ChinaMedicineIndexService chinaMedicineIndexService;

    /**
     * 查询中医堂信息列表
     *
     * @param queryParam 中医堂信息 查询参数
     * @return 中医堂信息
     */
    @Override
    public List<ChinaMedicineListPcVO> selectListPC(ChinaMedicineQueryParam queryParam) {
        queryParam.setDeleted(FlagEnum.NO.getKey());
        List<ChinaMedicineListPcVO> chinaMedicines = mapper.selectListPC(queryParam);
        return chinaMedicines;
    }

    /**
     * 新增中医堂信息
     *
     * @param updateParam 中医堂信息 新增参数
     * @return 结果
     */
    @Override
    public Long insertPC(ChinaMedicineUpdateParam updateParam) {
        //1. 中医堂新增
        ChinaMedicineEntity entity = updateParam.covert();
        String code = sysCodeRuleSV.createCode(CodeRuleEnum.CHINA_NO);
        entity.setTheCode(code);
        entity.setCreSb(ShiroUtil.getLoginId(true));
        Long result = this.insert(entity);

        if(result > 0){
            ChinaMedicineEntity chinaMedicineEntity = selectById(updateParam.getId());
            chinaMedicineIndexService.saveOrUpdate(chinaMedicineEntity);
        }

        // 2.挂号方式新增
        List<RegistryWayUpdateParam> registryWayParam = updateParam.getRegistryWayParam();
        if (!ObjectUtils.isEmpty(registryWayParam)) {
            List<RegistryWayEntity> collect = registryWayParam.stream().map(o ->
                    {
                        RegistryWayEntity covert = o.covert("deleted");
                        covert.setRelationId(entity.getId());
                        covert.setTheType(TheBelongEnum.CHINESE_MEDICINE_HALL.getKey());
                        covert.setCreSb(ShiroUtil.getLoginId(true));
                        return covert;
                    }
            ).collect(Collectors.toList());
            registryWaySV.batchInsertSelective(collect);
        }

        return entity.getId();
    }

    /**
     * 修改中医堂信息
     *
     * @param updateParam 中医堂信息 修改参数
     * @return 结果
     */
    @Override
    public int updateByIdPC(ChinaMedicineUpdateParam updateParam) {
        //1. 修改中医堂信息
        ChinaMedicineEntity entity = updateParam.covert();
        entity.setUptSb(ShiroUtil.getLoginId(true));
        int result = updateById(entity);
        if(result > 0) {
            ChinaMedicineEntity chinaMedicineEntity = selectById(updateParam.getId());
            chinaMedicineIndexService.saveOrUpdate(chinaMedicineEntity);
        }

        // 2.挂号方式修改
        List<RegistryWayUpdateParam> registryWayParam = updateParam.getRegistryWayParam();
        if (!ObjectUtils.isEmpty(registryWayParam)) {
            List<RegistryWayEntity> collect = registryWayParam.stream().map(o -> o.covert()).collect(Collectors.toList());

            for (RegistryWayEntity registryWay : collect) {
                if (registryWay.getId() == null || registryWay.getId() < 0) {
                    registryWay.setCreSb(ShiroUtil.getLoginId(true));
                    registryWay.setRelationId(entity.getId());
                    registryWay.setTheType(TheBelongEnum.CHINESE_MEDICINE_HALL.getKey());
                    registryWaySV.insert(registryWay);
                } else {
                    registryWay.setUptSb(ShiroUtil.getLoginId(true));
                    registryWaySV.updateById(registryWay);
                }
            }
        }

        return result;
    }

    @Override
    public void update(ChinaMedicineUpdateParam updateParam) {
        update(updateParam);
    }

    @Override
    public List<ChinaMedicineVO> selectCustomerByModel(ChinaMedicineMobileQueryParam queryParam) {
        List<Long> ids = chinaMedicineIndexService.searchByKeywordOfIds(queryParam);
        if (StringUtil.isNotBlank(queryParam.getKeyword())&& ids.isEmpty()) {
            return Collections.emptyList();
        }
        if(!ids.isEmpty()){
            queryParam.setIds(ids.toArray(new Long[ids.size()]));
        }
        if(StringUtil.isNotBlank(queryParam.getKeyword())){
            queryParam.setKeywordSort(true);
        }

        List<ChinaMedicineVO> data = mapper.selectCustomerByModel(queryParam);
        return data;
    }


    @Override
    public ChinaMedicineVO infoPc(Long id) {
        ChinaMedicineVO chinaMedicineVO = new ChinaMedicineVO();
        ChinaMedicineEntity data = selectById(id);
        BeanUtil.copyProperties(data, chinaMedicineVO);

        List<RegistryWayEntity> registryWayEntities = registryWaySV.selectList(
                TK.select(RegistryWayEntity.class)
                        .where()
                        .andEqualTo(RegistryWayEntity::getDeleted, FlagEnum.NO.getKey())
                        .andEqualTo(RegistryWayEntity::getTheType, TheBelongEnum.CHINESE_MEDICINE_HALL.getKey())
                        .andEqualTo(RegistryWayEntity::getRelationId, data.getId())
                        .end()
        );
        chinaMedicineVO.setRegistryWays(registryWayEntities);
        return chinaMedicineVO;
    }

    @Override
    public int delete(Long[] ids) {
        int result = updateByIds(ChinaMedicineEntity.builder().deleted(FlagEnum.IS.getKey()).build(), ids);

        if(result > 0){
            chinaMedicineIndexService.deleteAndSwapHeight(ids);
        }
        return result;
    }

    @Override
    public int publish(PublishParam params) {
        int result = updateByIds(ChinaMedicineEntity.builder().publishStatus(params.getState()).build(), params.getIds());

        if(result > 0){
            List<ChinaMedicineEntity> chinaMedicineEntities = selectList(TK.select(ChinaMedicineEntity.class).where().andIn(ChinaMedicineEntity::getId, params.getIds()).end());
            chinaMedicineIndexService.saveOrUpdate(chinaMedicineEntities);
        }

        return result;
    }


}
